import React from "react";
import express from "express";
import path from "path";
import { renderToString, renderToPipeableStream } from "react-dom/server";
import App from "./src/Router";
import { StaticRouter } from "react-router-dom/server";
import Html from "./src/Html";
import fs from "node:fs";

async function createServer() {
  const app = express();
  function render(url) {
    return renderToString(
      <StaticRouter location={url}>
        <App />
      </StaticRouter>
    );
  }
  function renderToP(url, res) {
    const { pipe } = renderToPipeableStream(
      <Html>
        <StaticRouter location={url}>
          <App />
        </StaticRouter>
      </Html>,
      {
        onShellReady() {
          res.setHeader("content-type", "text/html");

          pipe(res);
        },
      }
    );
  }

  app.use("/public", express.static(path.resolve(__dirname, "../client")));
  app.use("*", (req, res) => {
    const url = req.originalUrl;
    // const template = fs.readFileSync(
    //   path.resolve(__dirname, '../client/index.html'),
    //   'utf-8'
    // );
    // const appHtml = render(url);
    // const html = template.replace('#root', appHtml);
    // res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
    renderToP(url, res);
  });
  app.listen(5173, () => {
    console.log("http://localhost:5173");
  });
}

createServer();

/**
 * webpack ssr 会出现闪屏问题
 * 是因为有部分css会异步加载,目前没有解决办法
 * vite ssr 没有这个问题,css 是同步加载进去的
 *
 *  2025.07.24:
 *      找到原因了,是因为webpack打包时，把css拆分了，默认client/index.html只同步加载了一个css
 *      其他css是通过js异步加载的，所以在ssr的时候，会出现第一次没有样式的问题
 *      vite没有问题是因为，vite打包时配置了，不拆分css
 *      解决办法:
 *        TODO 待处理，感觉有好多优化点，不如直接用开源的解决方案
 */
